package com.guat.servlet.user;

import com.google.gson.Gson;
import com.guat.entity.User;
import com.guat.service.UserService;
import org.codehaus.jackson.map.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置前端返回数据使用UTF-8编码,防止乱码
        req.setCharacterEncoding("UTF-8");
        //获取前端传递的数据
//        String username = req.getParameter("username");
//        String password = req.getParameter("password");
//
//        System.out.println(username);
//        System.out.println(password);
//
//        UserService userService = new UserService();
//        Map<String, Object> userLoginMap = userService.getUser(username, password);
//
//        //设置返回前端数据使用UTF-8编码,防止乱码
//        resp.setCharacterEncoding("UTF-8");
//        //设置响应内容为json,以便前端正确解析返回的数据
//        resp.setContentType("application/json");
//        //将Map集合转换为json
//        Gson gson = new Gson();
//        String mapJson = gson.toJson(userLoginMap);
//        //将数据写入输入流中
//        resp.getWriter().write(mapJson);

        // 读取请求体中的数据
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));// 读取请求体中的数据
        StringBuilder requestBody = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            requestBody.append(line);
        }
        reader.close();

        // 解析JSON字符串为Java对象
        String jsonString = requestBody.toString(); // 假设请求体中的数据是JSON字符串
        // 使用Jackson或Gson库来解析JSON字符串为Java对象，这里以Jackson为例
        ObjectMapper objectMapper = new ObjectMapper();
        // 自动匹配类属性,生成新对象(前后端的名字要相同)
        User user = objectMapper.readValue(jsonString, User.class);
        //前端传过来的数据已经放到一个User对象中,通过get方法取出
        String username = user.getUsername();
        String password = user.getPassword();


        UserService userService = new UserService();
        Map<String, Object> userLoginMap = userService.getUser(username, password);

        //设置返回前端数据使用UTF-8编码,防止乱码
        resp.setCharacterEncoding("UTF-8");
        //设置响应内容为json,以便前端正确解析返回的数据
        resp.setContentType("application/json");
        //将Map集合转换为json
        Gson gson = new Gson();
        String mapJson = gson.toJson(userLoginMap);
        //将数据写入输入流中
        resp.getWriter().write(mapJson);

    }
}
